import type { ApiResponse } from '../types/anime';
import { axiosInstance } from './axiosInstance';
import { API_PATHS } from './apiConfig';
import toastService from './toastService';

// 添加收藏
export const addFavorite = async (animeId: number): Promise<boolean> => {
  try {
    const response = await axiosInstance.post<ApiResponse<null>>(API_PATHS.FAVORITE.ADD.replace(':animeId', animeId.toString()));
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('收藏失败:', response.data.msg);
      return false;
    }
    return true;
  } catch (error) {
    console.error('收藏失败:', error);
    // 如果是已经收藏过的错误或其他业务逻辑错误，返回false
    if (error instanceof Error && 'response' in error && 
        (error as any).response && (error as any).response.status === 400) {
      // 400错误由后端返回具体错误消息，不再重复提示
      return false;
    }
    throw error;
  }
}

// 取消收藏
export const removeFavorite = async (animeId: number): Promise<boolean> => {
  try {
    const response = await axiosInstance.delete<ApiResponse<null>>(API_PATHS.FAVORITE.REMOVE.replace(':animeId', animeId.toString()));
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('取消收藏失败:', response.data.msg);
      return false;
    }
    return true;
  } catch (error) {
    console.error('取消收藏失败:', error);
    // 如果是未收藏的错误，返回false
    if (error instanceof Error && 'response' in error && 
        (error as any).response && (error as any).response.status === 400) {
      // 400错误由后端返回具体错误消息，不再重复提示
      return false;
    }
    throw error;
  }
}

// 检查收藏状态
export const checkFavorite = async (animeId: number): Promise<boolean> => {
  try {
    const response = await axiosInstance.get<ApiResponse<boolean>>(API_PATHS.FAVORITE.CHECK.replace(':animeId', animeId.toString()));
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('检查收藏状态失败:', response.data.msg);
      return false;
    }
    return response.data.data;
  } catch (error) {
    console.error('检查收藏状态失败:', error);
    throw error;
  }
}

// 获取用户收藏的动漫信息列表
export const getUserFavoriteIds = async (page: number = 1, pageSize: number = 9): Promise<{data: any[], total: number, page: number, pageSize: number, totalPages: number}> => {
  try {
    const response = await axiosInstance.get<ApiResponse<{data: any[], total: number, page: number, pageSize: number, totalPages: number}>>(API_PATHS.FAVORITE.USER_LIST, {
      params: { page, pageSize }
    });
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('获取用户收藏列表失败:', response.data.msg);
      return { data: [], total: 0, page, pageSize, totalPages: 0 };
    }
    // 直接返回response.data.data，因为后端现在返回的是包含完整动漫信息的数据对象
    return response.data.data;
  } catch (error) {
    console.error('获取用户收藏列表失败:', error);
    // 降级处理：返回空数据和0总数
    return { data: [], total: 0, page, pageSize, totalPages: 0 };
  }
}

// 获取动漫收藏数量
export const getAnimeFavoriteCount = async (animeId: number): Promise<number> => {
  try {
    const response = await axiosInstance.get<ApiResponse<number>>(API_PATHS.FAVORITE.COUNT.replace(':animeId', animeId.toString()));
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('获取动漫收藏数量失败:', response.data.msg);
      return 0;
    }
    return response.data.data;
  } catch (error) {
    console.error('获取动漫收藏数量失败:', error);
    throw error;
  }
}

// 批量检查收藏状态
export const batchCheckFavorites = async (animeIds: number[]): Promise<Record<number, boolean>> => {
  try {
    const response = await axiosInstance.post<ApiResponse<Record<number, boolean>>>(API_PATHS.FAVORITE.BATCH_CHECK, animeIds);
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      console.error('批量检查收藏状态失败:', response.data.msg);
      // 返回默认值，全部设为未收藏
      const defaultMap: Record<number, boolean> = {};
      animeIds.forEach(id => {
        defaultMap[id] = false;
      });
      return defaultMap;
    }
    return response.data.data || {};
  } catch (error) {
    console.error('批量检查收藏状态失败:', error);
    // 发生错误时，返回默认值
    const defaultMap: Record<number, boolean> = {};
    animeIds.forEach(id => {
      defaultMap[id] = false;
    });
    return defaultMap;
  }
}